var allMenuList = null, allMenuIconList = null;
$(function () {
    getAllMenu();
    $('#closeMenuForm').click(function () {
        closeMenuForm();
    });
    $('.btn-group button').click(function () {
        let type = $(this).attr('type');
        //重置
        if (type == 'reset'){
            resetMenuForm();
        }else {//提交
            submitMenuForm();
        }
    });

    //监听菜单名、菜单路径值变化
    $('.not-null input').keyup(function () {
        let v = $(this).val();
        if (isNull(v)){
            return;
        }
        //删除input标签的错误提示
        $(this).parent().parent().removeClass('has-error');
        $(this).next().remove();
        let p = $(this).attr('placeholder'),errTipDiv = $('.error-tip');
        p = p.replace('请输入','');
        let errTip = errTipDiv.text();
        if (!isNull(errTip) && errTip.indexOf(p) >= 0){
            errTipDiv.text('');
        }
    })
    getAllMenuIcon();
    initParentMenuSelect();
    //监听.chosen-single span文本变化，控制菜单路径是否可填,必须放在initParentMenuSelect()之后才生效
    $(".chosen-single span").bind('DOMNodeInserted',function(){
        //如果父菜单是“无”，则不可填写菜单路径
        $('#menuUrl').attr('disabled', $('#selectParentMenu').val() == 0);
    });
    //添加菜单
    $('#btnAddMenu').click(function () {
        $('.widget-title').text('添加菜单');
        $('#menuId').val('');
        resetMenuForm();
        $('.page-mask,.menu-from').show();
    });
});

/**
 * 编辑菜单
 * @param menuId 菜单ID
 */
function editMenu(menuId) {
    $('.widget-title').text('编辑菜单');
    $('#menuId').val(menuId);
    resetMenuForm();
    $('.page-mask,.menu-from').show();
}
/**
 * 关闭菜单表单
 */
function closeMenuForm() {
    $('.page-mask,.menu-from').hide();
}
/**
 * 初始下菜单添加/修改表单中的父菜单下拉框
 */
function initParentMenuSelect() {
    if(!ace.vars['touch']) {
        $('.chosen-select').chosen({allow_single_deselect:true,search_contains: true});
        //resize the chosen on window resize
        $(window).off('resize.chosen').on('resize.chosen', function() {
            $('.chosen-select').each(function() {
                let $this = $(this);
                $this.next().css({'width': $this.parent().width()});
            });
        }).trigger('resize.chosen');
        //resize chosen on sidebar collapse/expand
        $(document).on('settings.ace.chosen', function(e, event_name, event_val) {
            if(event_name != 'sidebar_collapsed') return;
            $('.chosen-select').each(function() {
                let $this = $(this);
                $this.next().css({'width': $this.parent().width()});
            })
        });

        $('#chosen-multiple-style .btn').on('click', function(){
            let target = $(this).find('input[type=radio]');
            let which = parseInt(target.val()), ffs = $('#form-field-select-4');
            if(which == 2) {
                ffs.addClass('tag-input-style');
            }else{
                ffs.removeClass('tag-input-style');
            }
        });
    }
}
/**
 * 获取所有的菜单
 */
function getAllMenu() {
    $.ajax({
        type: "POST",
        url: '/menu/listAllMenu',
        dataType:'json',
        async: false,
        success: function(menuData){
            allMenuList = menuData;
            let menuArr = [];
            for (let g = 0; g < allMenuList.length; g ++){
                menuArr.push(getMenuTrStr(allMenuList[g],g,'',''));
            }
            $('table tbody').append(menuArr.join(''));
            addMenuOption();
        }
    });
}

/**
 * 获取菜单的tr字符串
 * @param m 菜单对象
 * @param parentMenuName 父菜单名
 * @param childrenMenuTotal 子菜单总数
 * @returns {string} 菜单的tr字符串
 */
function getMenuTrStr(m,g,parentMenuName,childrenMenuTotal) {
    let id = m.menuId, hasChildrenMenu = parentMenuName == '';
    //是否需要合并列单元格，如果是子菜单，则合并父级菜单列
    let isRowSpan = !hasChildrenMenu && g == 0;
    return '<tr id="tr' + id + '">' +
        '   <td class="center">' + (g + 1) + '</td>' +
        '   <td class="center"><i class="' + m.menuIcon + '"></i></td>' +
        //如果是父级菜单，则不显示父级菜单列,合并子菜单中的父级菜单列
        (hasChildrenMenu || !isRowSpan ? '' : '<td class="center"' + (isRowSpan ? ' rowspan="' + childrenMenuTotal + '" style="vertical-align:middle;"' : '') + '>' + parentMenuName + '</td>') +
        '   <td class="center">' + m.menuName + '</td>' +
        '   <td>' + m.menuUrl + '</td>' +
        '   <td class="center">' + (isNull(m.menuOrder) ? '' : m.menuOrder) + '</td>' +
        '   <td style="width: 15%;">' +
        //如果父菜单名不为空，则显示“展开”按钮，否则不显示
        (hasChildrenMenu ? '<a id="open' + id + '" class="btn btn-mini btn-warning bigger-120" onclick="openChildrenMenu(' + id + ')" >展开</a>' : '') +
        '       <a class="btn btn-mini btn-primary no-radius" title="编辑" onclick="editMenu(' + id + ')" ><i class="ace-icon fa fa-pencil-square-o bigger-200"></i></a>' +
        '       <a class="btn btn-mini btn-danger btn-sm" title="删除" onclick="deleteMenuById(' + id + ')"><i class="ace-icon fa fa-trash-o bigger-200"></i></a>' +
        '   </td>' +
        '</tr>';
}
/**
 * 展开子菜单
 * @param parentId 父菜单ID
 */
function openChildrenMenu(parentId) {
    let parentMenu = $('#tr' + parentId),openA = $('#open' + parentId);
    //如果已展开
    let className = parentMenu.attr('class'),aText = openA.text();
    if (aText == '缩回'){
        openA.text('展开');
        $('.tr-' + parentId).remove();
        parentMenu.removeClass('opened');
        return;
    }
    if (className != null && className.indexOf('opened') > -1){
        return;
    }
    for (let g = 0; g < allMenuList.length; g ++){
        if (parentId != allMenuList[g].menuId){
            continue;
        }
        let childrenMenuList = allMenuList[g].childrenMenuList;
        let childrenMenuStr = '<tr class="tr-' + parentId + '"><td colspan="6">' +
            '<table class="table table-striped table-bordered table-hover children-table">' +
            '    <thead>' +
            '        <tr>' +
            '            <th class="center" style="width: 50px;">序号</th>' +
            '            <th class="center">图标</h>' +
            '            <th class="center">父级菜单</th>' +
            '            <th class="center">名称</th>' +
            '            <th class="center">菜单路径</th>' +
            '            <th class="center">排序</th>' +
            '            <th class="center">操作</th>' +
            '        </tr>' +
            '    </thead>' +
            '    <tbody>';
        let childrenMenuTotal = childrenMenuList.length;
        for (let q = 0; q < childrenMenuTotal; q ++){
            childrenMenuStr += getMenuTrStr(childrenMenuList[q],q,allMenuList[g].menuName,childrenMenuTotal);
        }
        parentMenu.after(childrenMenuStr + '</tbody></table></td></tr>');
        //添加已展开标识
        parentMenu.addClass('opened');
    }
    openA.text('缩回');
}

/**
 * 删除菜单
 * @param menuId 菜单ID
 * @param parentMenuName 父级菜单名
 */
function deleteMenuById(menuId) {
    swal({
        title: '确认删除',
        text: '您确定要删除该菜单吗？如果删除，其下所有子菜单也会删除！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        cancelButtonText: '取消',
        confirmButtonText: '删除'
    }).then(function(isConfirm) {
        if (!isConfirm) {
            return;
        }
        $.ajax({
            type: "POST",
            url: '/menu/deleteMenuById',
            dataType:'json',
            cache: true,
            data:{menuId: menuId},
            success: function(delFlag){
                if (delFlag == '0'){
                    swal('成功提示','删除成功','success');
                    deleteMenu(menuId);
                }else {
                    swal('失败提示','删除成功','error');
                }
            }
        });
    });
}

/**
 * 删除前台及页面上的菜单
 * @param menuId 菜单ID
 */
function deleteMenu(menuId) {
    //删除allMenuList中的菜单
    for(let g = 0; g < allMenuList.length; g ++){
        let parentMenuObj = allMenuList[g];
        if (parentMenuObj.menuId == menuId){
            allMenuList.splice(g,1);
            break;
        }
        let childrenMenuList = parentMenuObj.childrenMenuList;
        if (isNull(childrenMenuList)){
            continue;
        }
        for(let i = 0; i < childrenMenuList.length; i ++){
            if (childrenMenuList[i].menuId == menuId){
                childrenMenuList.splice(i,1);
                break;
            }
        }
        parentMenuObj.childrenMenuList = childrenMenuList;
    }
    let thisTr = $('#tr' + menuId);
    //获取当前删除行的中第2个td的rowspan属性值
    let rowspan = thisTr.children().eq(1).attr('rowspan');
    if (!isNull(rowspan) && rowspan > 1){
        //获取父级菜单名称
        let parentMenuName = thisTr.children().eq(1).html();
        //给thisTr下一行的第1个td后面添加td
        thisTr.next().children().eq(0).after('<td class="center" rowspan="' + (rowspan - 1) + '" style="vertical-align:middle;">' + parentMenuName + '</td>');
    }
    let tbody = thisTr.parent();
    thisTr.remove();
    let trRows = 1;
    //遍历tbody里的tr行
    $(tbody).children('tr').each(function () {
        //将tr行里的第1个td重新编号
        $(this).children().eq(0).text(trRows);
        trRows ++;
    });
}
/**
 * 获取所有的菜单图标
 */
function getAllMenuIcon() {
    $.ajax({
        type: "POST",
        url: '/dictionaries/listDictionaries',
        data: {parentId: 87},
        dataType:'json',
        success: function(dicList){
            if (dicList == null || dicList.length < 1){
                return;
            }
            allMenuIconList = dicList;
            let iconArr = [];
            for (let g = 0; g < dicList.length; g ++){
                let iconObj = dicList[g];
                iconArr.push('<label>' +
                    '   <input name="form-field-radio" type="radio" class="ace">' +
                    '   <span class="lbl"><i id="' + iconObj.id +'" class="' + iconObj.dicCode +'"></i></span>' +
                    '</label>');
            }
            $('#menuIconList').append(iconArr.join(''))
        }
    });
}

/**
 * 添加菜单选项
 */
function addMenuOption() {
    let spm = $('#selectParentMenu');
    spm.empty().append('<option value="0">无</option>');
    let menuArr = [];
    for (let g = 0; g < allMenuList.length; g ++){
        let menuObj = allMenuList[g];
        menuArr.push('<option value="' + menuObj.menuId + '">' + menuObj.menuName + '</option>');
    }
    spm.append(menuArr.join(''));
}

/**
 * 重置菜单表单
 */
function resetMenuForm() {
    let menuId = $('#menuId').val();
    if (isNull(menuId)){
        $('#menuName,#menuUrl,#menuOrder').val('');
        $('.ace').attr('checked',false);
        $('.chosen-container .chosen-single span').text('无');
        return;
    }
    let menuObj = getMenuById(menuId);
    I('menuName').value = menuObj.menuName;
    I('menuUrl').value = menuObj.menuUrl;
    I('menuOrder').value = menuObj.menuOrder;
    //选择图标单选按钮的中图标
    $('#menuIconList i[class="' + menuObj.menuIcon + '"]').parent().prev().attr('checked',true);
    let parentName = '无', pId = menuObj.parentId;
    if (!isNull(pId) && pId != '0'){
        let parentObj = getMenuById(pId);
        parentName = parentObj.menuName;
    }
    //设置父菜单的默认选项
    $('#selectParentMenu option[value="' + pId + '"]').prop('selected',true);
    $('.chosen-container .chosen-single span').text(parentName);
}

/**
 * 根据菜单ID获取菜单对象
 * @param menuId 菜单ID
 */
function getMenuById(menuId) {
    for(let g = 0; g < allMenuList.length; g ++){
        let parentMenuObj = allMenuList[g];
        if (parentMenuObj.menuId == menuId){
            return parentMenuObj;
        }
        let childrenMenuList = parentMenuObj.childrenMenuList;
        if (isNull(childrenMenuList)){
            continue;
        }
        for(let i = 0; i < childrenMenuList.length; i ++){
            if (childrenMenuList[i].menuId == menuId){
                return childrenMenuList[i];
            }
        }
    }
    return null;
}

/**
 * 提交菜单表单
 */
function submitMenuForm() {
    let menuName = $('#menuName').val(),menuUrl = $('#menuUrl').val(), menuIcon = '',
        parentId = $('#selectParentMenu').val(), controllerMethod = 'edit',addOrEdit = '编辑';
    if (isNull(menuName)){
        setTip('menuName','菜单名不能为空');
        return;
    }
    //如果父菜单不等于0，则菜单路径不能为空
    if (parentId != 0 && isNull(menuUrl)){
        setTip('menuUrl','菜单路径不能为空');
        return;
    }
    if($('.widget-title').text() == '添加菜单'){
        controllerMethod = 'add';
        addOrEdit = '添加';
    }
    let selectRadio = $('#menuIconList input[type="radio"]:checked').next().children();
    if (selectRadio.length > 0){
        menuIcon = selectRadio[0].id;
    }
    menuUrl = parentId == 0 ? '' : menuUrl;
    let menuObj = {
        menuId: $('#menuId').val(),
        parentId: parentId,
        menuName: menuName,
        menuUrl: menuUrl,
        menuIcon:menuIcon,
        menuOrder: $('#menuOrder').val()
    };
    showLoading('提交中');
    $.ajax({
        type: "POST",
        url: '/menu/' + controllerMethod,
        contentType : "application/json",
        data: JSON.stringify(menuObj),
        dataType:'json',
        success: function(addRow){
            hideLoading();
            if (addRow > 0){
                swal('成功提示',addOrEdit + '成功!','success').then(function () {
                    location.reload();
                });
            } else {
                swal('失败提示',addOrEdit + '失败!','error');
            }
        },
        error: function () {
            hideLoading();
            swal('错误提示',addOrEdit + '出错!','error');
        }
    });
}

/**
 * 设置input错误提示样式
 * @param id input id
 * @param errTip 错误提示文字
 */
function setTip(id,errTip) {
    $('.error-tip').text(errTip);
    let inputObj = $('#' + id);
    inputObj.after('<i class="ace-icon fa fa-times-circle"></i>');
    inputObj.parent().parent().addClass('has-error');
}